export default class HttpClient {
	// 拦截器列表(外部重写)
	static interceptorList = [];

	// 请求域名(外部重写)
	static base = ""

	#config = {
		url: "",  // 请求的本域名
		method: 'get',
		
		header: {  // 配置请求头信息
			'content-type': 'application/json'
		},
		
		showLoading: true,  // 是否显示请求中的loading
		loadingText: '请求中...',  // 请求loading中的文字提示
		loadingTime: 500,  // 在此时间内，请求还没回来的话，就显示加载中动画，单位ms
		auth: true,  //是否验证登录
		cache: false,  //是否缓存
		data: {},  //发送给后端的数据
		rawResponse: false,
		catchResponse: true,  //拦截请求异常
	}
	
	static create() {
		return new HttpClient()
	}

	setConfig(config) {  // 合并替换配置
		console.log('拿到的配置', config)
		this.#config = { ...this.#config, ...config }
		return this
	}

	//发起请求
	async request() {
		let timer = null
		try {
			// loading
			if (this.#config.showLoading) {
				timer = setTimeout(() => uni.showLoading({ title: this.#config.loadingText, mask: true }), this.#config.loadingTime)
			}
			
			// 请求前拦截器运行
			for (let interceptor of HttpClient.interceptorList) {
				if (!(interceptor instanceof BaseInterceptor)) return
				this.#config = await interceptor.request(this.#config)
			}
			
			// 开始发请求
			let response = await uni.request({
				// url: `${this.#config.url === '/upload/audio-muxer' ? 'http://api.ynxpt.dingwei.cn/storage/admin/file/audio-muxer' : HttpClient.base + this.#config.url}`,
				url: `${HttpClient.base + this.#config.url}`,
				data: this.#config.data,
				header: this.#config.header,
				method: this.#config.method,
			})
			
			// 请求后拦截器运行
			for (let interceptor of HttpClient.interceptorList) {
				if (!(interceptor instanceof BaseInterceptor)) return
				response = await interceptor.reponse(this.#config, response)
			}
			
			return response
		} catch (e) {
			throw e
		} finally {
			// 清理定时器
			if (this.#config.showLoading) {
				clearTimeout(timer)
				uni.hideLoading()
			}
		}
	}
}

export class BaseInterceptor {
	async request(options) {
		return options
	}
	async reponse(options, reponse) {
		return reponse
	}
}
